package com.jihox.abookpro;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.jihox.abookpro.R;
import com.jihox.abookpro.dao.OrderDAO;
import com.jihox.abookpro.domain.Order;
import com.jihox.abookpro.fragment.HomeFragment;
import com.jihox.abookpro.fragment.MessageFragment;
import com.jihox.abookpro.fragment.NoAccountFragment;
import com.jihox.abookpro.fragment.OrderFragment;
import com.jihox.abookpro.fragment.OrderFragment.OnListDataChangeListener;
import com.jihox.abookpro.uploader.UploadService;
import com.jihox.abookpro.util.ConfigProperties;
import com.jihox.abookpro.util.NativeImageLoader;
import com.jihox.abookpro.util.UpdateManager;
import com.jihox.abookpro.view.JHProgressDialog;

public class HomeChangeActivity extends BaseActivity implements
		OnCheckedChangeListener,OnListDataChangeListener {
	
	private static final String HOMEFRAGMENT = "homefragment";
	private static final int HOME_CODE = 1235321;
	private static final int CAPTURE_CODE = 13325831;

	private Button headButton;
	private FragmentManager manager;
	private RadioButton radioButtonCustomize;
	private RadioButton radioButtonOrder;
	private RadioButton radioButtonMessage;
	public RadioGroup bottomRG;
	public View rgLine;
	private OrderFragment orderFragment;
	private MessageFragment messageFragment;
	private NoAccountFragment noAccountFragment;
	private HomeFragment homeFragment;//主页
	
	private String cstToken;
	private String user_id_code;

	private UploadService uploadService;
	private boolean bindedService = false;
	private JHProgressDialog pd;

	private List<Order> orderList;

	public int fragmentindex;
	public TextView titleText;
	public Button logoutButton;
	private String isNotification = "";
	
	public String myurl = null;

	private Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			switch(msg.what){
			case 1:	
				List<String> noUploadid = msg.getData().getStringArrayList("NoUpLoad");
				if(noUploadid.size()>0){
					Log.i("msg", noUploadid.toString());
					uploadFiles(noUploadid);
				}
			break;
			case 2:
				Toast.makeText(HomeChangeActivity.this, "用户信息已过期,请重新登录", Toast.LENGTH_LONG).show();
				MyApplication.getInstance().setCstToken("");
				MyApplication.getInstance().setUserId("");
				setSelection(0);
			break;
			}
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home_change);
		

		manager = getFragmentManager();
		headButton = (Button) findViewById(R.id.head_btn_operation);
		logoutButton = (Button) findViewById(R.id.head_btn_logout);
		rgLine = findViewById(R.id.m_radiogroup_line);
		bottomRG = (RadioGroup) findViewById(R.id.m_radiogroup);
		radioButtonCustomize = (RadioButton) findViewById(R.id.radio_button_customize);
		radioButtonOrder = (RadioButton) findViewById(R.id.radio_button_order);
		radioButtonMessage = (RadioButton) findViewById(R.id.radio_button_message);
		radioButtonCustomize.setOnCheckedChangeListener(this);
		radioButtonOrder.setOnCheckedChangeListener(this);
		radioButtonMessage.setOnCheckedChangeListener(this);
		titleText = (TextView)findViewById(R.id.header_txt);
		titleText.setText(R.string.app_name);		
		Intent intent = getIntent();
		isNotification = intent.getStringExtra("isNotification");
		if (isNotification != null && isNotification.equals("notification")) {
			setSelection(1);
			NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
			mNotificationManager.cancel(1);
		}else {
			fragmentindex = intent.getIntExtra("FragmentIndex", 0);
			setSelection(fragmentindex);
		}
		headButton.setText(R.string.Edit);
		headButton.setVisibility(View.GONE);

		headButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				Button btn = (Button) view;
				boolean isEdit = OrderFragment.ordersListAdapter.isEdit();
				OrderFragment.ordersListAdapter.setEdit(!isEdit);
				if (isEdit) {
					btn.setText(R.string.Edit);
				} else {
					btn.setText(R.string.Done);
				}
			}
		});
		logoutButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				switch(fragmentindex){
				case 0://扫描二维码
					Intent scan_intent = new Intent();
					scan_intent.setClass(HomeChangeActivity.this, CaptureActivity.class);
					startActivityForResult(scan_intent, CAPTURE_CODE);
					break;
				case 1://注销登录,清除cstToken,清除user_id_code
					MyApplication.getInstance().setCstToken("");
					MyApplication.getInstance().setUserId("");
					Intent logout_intent = new Intent(HomeChangeActivity.this, LoginActivity.class);
					logout_intent.putExtra("comefrom", HOMEFRAGMENT);
					startActivityForResult(logout_intent, HOME_CODE);
					break;
				case 9:
					fragmentindex = 0;
					myurl = null;
					homeFragment.currentUrl = null;
					homeFragment.loadMyUrl();
					logoutButton.setBackgroundResource(R.drawable.saoyisao_btn_selector);
					rgLine.setVisibility(View.VISIBLE);
					bottomRG.setVisibility(View.VISIBLE);
					titleText.setVisibility(View.VISIBLE);
//					setSelection(0);
					break;
				}
				
			}
		});
		
		String dirPath = Environment.getExternalStorageDirectory()
				+ NativeImageLoader.jihoxUrl;
		File dir = new File(dirPath);
		if (!dir.exists() && !dir.isDirectory()) {
			dir.mkdirs();// 创建文件夹
		}

		// 判断从哪跳转过来的
		String FromActivity = intent.getStringExtra("ComeFrom");
		if (FromActivity != null && FromActivity.equals("Start")) {
			UpdateManager um = new UpdateManager();
			um.checkAppUpdate(this, true);
			String cstToken = MyApplication.getInstance().getCstToken();
			String user_id_code = MyApplication.getInstance().getUserId();
			if(!cstToken.equals("") && !user_id_code.equals("")){
				new Thread(getOrdersRunnable).start();
//				uploadFiles();
			}
		}

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Intent intent = getIntent();
		isNotification = intent.getStringExtra("isNotification");
//		Log.d("isNotificationResume", isNotification + "");
		if (isNotification != null && isNotification.equals("notification")) {
			setSelection(1);
		}
	}
	
	private void uploadFiles(List<String> noUploadid) {		
		OrderDAO dao = new OrderDAO(this);
		orderList = dao.getUserNotUploadOrderInfoList(noUploadid);
		if (orderList.size() > 0) {
			Log.d("HomeActivity", "uploadFiles");
			dialog();
		}
	}
	
	private Runnable getOrdersRunnable = new Runnable() {
		private static final int REQUEST_TIMEOUT = 10 * 1000;
		private static final int SO_TIMEOUT = 10 * 1000;
		@Override
		public void run() {
//			String customerCode = MyApplication.getInstance().getCustomerCode();
			// TODO Auto-generated method stub
			String url = ConfigProperties.getOrdersListUrl().replace("{}", "0");
			HttpGet httpPost = new HttpGet(url);
//			UserHelper helper = new UserHelper();
			httpPost.setHeader("cstToken", MyApplication.getInstance().getCstToken());
			httpPost.setHeader("isFileUploaded", "false");
			try {
				BasicHttpParams httpParams = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParams,
						REQUEST_TIMEOUT);
				HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
				HttpClient httpclient = new DefaultHttpClient(httpParams);
				HttpResponse httpResponse = httpclient.execute(httpPost);
				String result = EntityUtils.toString(httpResponse.getEntity());
				Log.i("msg_order_no_upload", result);
				JSONObject responseJson = new JSONObject(result);
				if("true".equals(responseJson.getString("success"))){
					JSONArray ordersJson = responseJson.getJSONArray("Data");
//					Log.i("msg_data", ordersJson.toString());
					if (ordersJson != null) {
						List<String> nouploade = noUploadOrderId(ordersJson);
						if(nouploade.size()>0){
							Message msg = new Message();
							msg.what = 1 ;
							Bundle bl = new Bundle();
							bl.putStringArrayList("NoUpLoad", (ArrayList<String>) nouploade);
							msg.setData(bl);
							handler.sendMessage(msg);
						}
					}
				}else{
					Message msg = new Message();
					msg.what = 2;
					handler.sendMessage(msg);
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	};
	
	private List<String> noUploadOrderId(JSONArray resultJsons){
		List<String>  noupid = new ArrayList<String>();
		for (int i = 0; i < resultJsons.length(); i++) {
			JSONObject orderJson;
			try {
				orderJson = resultJsons.getJSONObject(i);
				noupid.add(orderJson.getString("id"));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		return noupid;
	}
	
	private void showDialog() {

		final Dialog dialog = new Dialog(HomeChangeActivity.this,
				R.style.JHDialog);
		// 设置它的ContentView
		dialog.setContentView(R.layout.dialog_general);
		Button buttonOK = (Button) dialog.findViewById(R.id.dialog_button_ok);
		Button buttonCancel = (Button) dialog
				.findViewById(R.id.dialog_button_cancel);
		TextView dialogTitle = (TextView) dialog
				.findViewById(R.id.dialog_title);
		TextView dialogMessage = (TextView) dialog
				.findViewById(R.id.dialog_message);

		buttonOK.setBackgroundResource(R.drawable.delete_style);
		buttonCancel.setBackgroundResource(R.drawable.grey_style);
		buttonOK.setText(R.string.T_Ok);
		buttonCancel.setText(R.string.T_Cancel);

		dialogTitle.setText(R.string.T_Config_back);
		dialogMessage.setText(R.string.T_Back_config);

		buttonOK.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				NativeImageLoader.getInstance().clearCache();
				dialog.dismiss();
				MyApplication.getInstance().onTerminate();
			}
		});
		buttonCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		dialog.show();
	}

	private void dialog() {

		final Dialog dialog = new Dialog(HomeChangeActivity.this,
				R.style.JHDialog);
		// 设置它的ContentView
		dialog.setContentView(R.layout.dialog_general);
		Button buttonOK = (Button) dialog.findViewById(R.id.dialog_button_ok);
		Button buttonCancel = (Button) dialog
				.findViewById(R.id.dialog_button_cancel);
		TextView dialogTitle = (TextView) dialog
				.findViewById(R.id.dialog_title);
		TextView dialogMessage = (TextView) dialog
				.findViewById(R.id.dialog_message);

		buttonOK.setBackgroundResource(R.drawable.green_style);
		buttonCancel.setBackgroundResource(R.drawable.grey_style);
		buttonOK.setText(R.string.T_upload_now);
		buttonCancel.setText(R.string.T_Next_say);
		dialogTitle.setText(getResources().getString(R.string.T_Have)
				+ String.valueOf(orderList.size())
				+ getResources().getString(R.string.T_Not_Upload_success));
		dialogMessage.setText(R.string.T_Upload_now_config);
		dialog.setCanceledOnTouchOutside(false);

		buttonOK.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				// 启动service
				Intent sIntent = new Intent();
				ComponentName cn = new ComponentName(HomeChangeActivity.this,
						"com.jihox.abookpro.uploader.UploadService");
				sIntent.setComponent(cn);
				int dialogWidth = (int) (getWindowManager().getDefaultDisplay()
						.getWidth() * 0.8);
				sIntent.putExtra("DialogWidth", dialogWidth);
				startService(sIntent);
				bindService(sIntent, conn, Context.BIND_AUTO_CREATE);
				pd = JHProgressDialog.show(HomeChangeActivity.this, null,
						getResources().getString(R.string.X_Submiting_Order));
			}
		});

		buttonCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		dialog.show();
	}

	ServiceConnection conn = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {

		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			pd.dismiss();
			// 返回一个MsgService对象
			uploadService = ((UploadService.UploadBinder) service).getService();
			for (Order order : orderList) {
				uploadService.addUploadTask(order);
			}
			Toast.makeText(HomeChangeActivity.this, R.string.T_Start_Upload,
					Toast.LENGTH_LONG).show();
		}
	};

	private void setSelection(int index) {
		// 开启一个Fragment事务
		FragmentTransaction transaction = manager.beginTransaction();
		// 淡入淡出效果
		// transaction.setCustomAnimations(android.R.animator.fade_in,
		// android.R.animator.fade_out);

		// 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
		//hideFragments(transaction);
		switch (index) {
		case 0:
			radioButtonCustomize.setChecked(true);
			titleText.setText(R.string.app_name);
			logoutButton.setVisibility(View.VISIBLE);
			logoutButton.setText("");
			if(fragmentindex == 9){
				logoutButton.setBackgroundResource(R.drawable.return_btn_selector);
			}else{
				logoutButton.setBackgroundResource(R.drawable.saoyisao_btn_selector);
			}
			headButton.setVisibility(View.INVISIBLE);	
			
			if (homeFragment == null) {
				homeFragment = new HomeFragment();
			}
			transaction.replace(R.id.fragment_container, homeFragment);

			break;
		case 1:
			radioButtonOrder.setChecked(true);
			titleText.setText(R.string.myAccount);
			
			cstToken = MyApplication.getInstance().getCstToken();
			user_id_code = MyApplication.getInstance().getUserId();
//			Log.i("msg", "----------------"+cstToken);
			if(cstToken.length()>0 && user_id_code.length()>0){
				logoutButton.setVisibility(View.VISIBLE);
				logoutButton.setBackgroundResource(R.drawable.head_button);
				logoutButton.setText(R.string.Logout);
				if (orderFragment == null) {
					orderFragment = new OrderFragment();
				} 
				transaction.replace(R.id.fragment_container, orderFragment);
			}else{
				logoutButton.setVisibility(View.INVISIBLE);
				headButton.setVisibility(View.INVISIBLE);
				if (noAccountFragment == null) {
					noAccountFragment = new NoAccountFragment();
				}
				transaction.replace(R.id.fragment_container, noAccountFragment);
			}
			break;
		case 2:
			radioButtonMessage.setChecked(true);
			titleText.setText(R.string.text_message);
			logoutButton.setVisibility(View.GONE);
			headButton.setVisibility(View.GONE);
			if (messageFragment == null) {
				messageFragment = new MessageFragment();
			} 
			transaction.replace(R.id.fragment_container, messageFragment);
			break;

		default:
			break;
		}
		transaction.addToBackStack(null);
		transaction.commit();

	}

	@Override
	protected void onDestroy() {
		if (bindedService) {
			this.unbindService(conn);
		}
		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(fragmentindex == 9){	
				fragmentindex = 0;
				myurl = null;
				homeFragment.currentUrl = null;
				homeFragment.loadMyUrl();
				logoutButton.setBackgroundResource(R.drawable.saoyisao_btn_selector);
				rgLine.setVisibility(View.VISIBLE);
				bottomRG.setVisibility(View.VISIBLE);
				titleText.setVisibility(View.VISIBLE);
			}else{
				showDialog();
			}
		}
		return false;
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (isChecked) {
			switch (buttonView.getId()) {
			case R.id.radio_button_customize:
				fragmentindex = 0;
				setSelection(fragmentindex);
				break;
			case R.id.radio_button_order:
				fragmentindex = 1;
				setSelection(fragmentindex);
				headButton.setText(R.string.Edit);
				break;
			case R.id.radio_button_message:
				fragmentindex = 2;
				setSelection(fragmentindex);
				break;

			default:
				break;
			}
		}
	}

	@Override
	public void onListDataChange(int size) {
		if(size>0){
			headButton.setVisibility(View.VISIBLE);
		}else {
			headButton.setVisibility(View.GONE);
		}
		
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(requestCode == CAPTURE_CODE && resultCode == RESULT_OK){
			fragmentindex = 9;
			homeFragment.currentUrl = null;
			myurl = data.getStringExtra("scan_result");
			homeFragment.loadMyUrl();
			logoutButton.setBackgroundResource(R.drawable.return_btn_selector);
			rgLine.setVisibility(View.GONE);
			bottomRG.setVisibility(View.GONE);
			titleText.setVisibility(View.GONE);
//			setSelection(0);
			
		}
		
		if(requestCode == HOME_CODE && resultCode == RESULT_OK){
			setSelection(1);			
		}

		super.onActivityResult(requestCode, resultCode, data);
	}
}
